import {history} from 'umi';
import {message} from 'antd';
import {ResponseStructureInterface} from '@/types/interface/response-structure.interface';
import {ErrorTypeEnum} from '@/types/Enum/error-type.enum';
import {AxiosErrorTypeEnum} from '@/types/Enum/axios-error-type.enum';


interface IRequestOptions {
    skipErrorHandler?: boolean;
}

export const responseError = {
    responseErrorThrower: (res: ResponseStructureInterface) => {
        const {code, data, message, success} = res;
        if (!success) {
            const error: any = {};
            error.name = 'BizError';
            error.info = {code, data, message};
            throw error;
        }
    },
    responseErrorHandler: (error: any, opts: IRequestOptions) => {
        //如果请求 设置skipErrorHandler为true，则不走默认错误处理
        if (opts?.skipErrorHandler) {
            throw error;
        }
        //默认错误处理
        if (error.name === 'BizError') {
            const errorInfo: ResponseStructureInterface | undefined = error.info;
            //处理与后端约定的状态码
            if (errorInfo) {
                switch (errorInfo.code) {
                    case ErrorTypeEnum.SILENT:
                        break;
                    case ErrorTypeEnum.REJECT:
                        //没有权限或者authorization到期了
                        message.error(errorInfo.message);
                        history.push('/login');
                        break;
                }
            }
        } else if (error.response) {
            // Axios 的错误
            switch (error.response.status) {
                case AxiosErrorTypeEnum.NotAuth:
                    history.push(`/${AxiosErrorTypeEnum.NotAuth}`);
                    break;
                case AxiosErrorTypeEnum.NotFound:
                    history.push(`/${AxiosErrorTypeEnum.NotFound}`);
                    break;
                case AxiosErrorTypeEnum.NotNetwork:
                    history.push(`/${AxiosErrorTypeEnum.NotNetwork}`);
            }
        } else if (error.request) {
            // 请求已经成功发起，但没有收到响应
            // \`error.request\` 在浏览器中是 XMLHttpRequest 的实例，
            // 而在node.js中是 http.ClientRequest 的实例
            message.error('None response! Please retry.');
        } else {
            // 发送请求时出了点问题
            message.error('Request error, please retry.');
        }
    },
};
